package com.hongyuan.coach.ui.member.view_mode;

import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;
import com.hongyuan.mvvmhabitx.binding.command.BindingCommand;
import com.hongyuan.mvvmhabitx.bus.RxBus;
import com.hongyuan.mvvmhabitx.bus.RxSubscriptions;
import com.hongyuan.mvvmhabitx.bus.event.SingleLiveEvent;
import com.hongyuan.mvvmhabitx.utils.ToastUtils;
import com.hongyuan.coach.R;
import com.hongyuan.coach.base.CustomViewModel;
import com.hongyuan.coach.data.Constants;
import com.hongyuan.coach.data.MyRepository;
import com.hongyuan.coach.data.md5.BaseUtil;
import com.hongyuan.coach.myview.scllor_view.UnitBean;
import com.hongyuan.coach.myview.scllor_view.UnitBeanUtils;
import com.hongyuan.coach.ui.course.beans.OsBeans;
import com.hongyuan.coach.ui.member.activity.MemberFilterActivity;
import com.hongyuan.coach.ui.member.activity.SearchMemberActivity;
import com.hongyuan.coach.ui.member.beans.FilterBeans;
import com.hongyuan.coach.ui.member.beans.MembersBean;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import me.tatarka.bindingcollectionadapter2.BR;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class MemberViewModel extends CustomViewModel<MyRepository> {

    private Disposable mSubscription;

    //课程选取工具
    public UnitBeanUtils osUtils;
    //课程数据集
    private ObservableField<List<OsBeans.ListBean>> osList = new ObservableField<>();
    //筛选条件
    private ObservableField<FilterBeans> filterBean = new ObservableField<>(new FilterBeans());
    //总会员数
    public ObservableField<Integer> memberAllNum = new ObservableField<>();
    //门店筛选（门店id）
    public ObservableField<String> osId = new ObservableField<>("");
    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>("");
    public ObservableField<String> osName = new ObservableField<>("全部门店");

    public MemberViewModel(@NonNull Application application, MyRepository model) {
        super(application, model);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //显示门店列表
        public SingleLiveEvent<List<UnitBean>> showOs = new SingleLiveEvent<>();
    }

    //给RecyclerView添加ObservableList
    public ObservableList<MemberItemViewModel> observableList = new ObservableArrayList<>();

    //给RecyclerView添加ItemBinding
    public ItemBinding<MemberItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_member);


    //筛选
    public BindingCommand goFilter = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putSerializable("filterBean",filterBean.get());
        startActivity(MemberFilterActivity.class,bundle);
    });

    //搜索
    public BindingCommand goSearch = new BindingCommand(() -> {
        startActivity(SearchMemberActivity.class);
    });

    //选着门店
    public BindingCommand selectOs = new BindingCommand(() -> {
        if(osUtils != null && osList.get() != null && osList.get().size() > 0){
            uc.showOs.setValue(osUtils.getUnitList(osList.get()));
        }else{
            ToastUtils.showShort("暂无选门店");
        }
    });


    @Override
    public void onCreate() {
        super.onCreate();

        mSubscription = RxBus.getDefault().toObservable(FilterBeans.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(message -> {
                    observableList.clear();
                    filterBean.set(message);

                    clearParams();
                    if(BaseUtil.isValue(osId.get())){
                        setParams("os_id",osId.get());
                    }
                    if(BaseUtil.isValue(message.getNum())){
                        setParams("num",message.getNum());
                    }
                    if(BaseUtil.isValue(message.getType())){
                        setParams("type",message.getType());
                    }
                    if(BaseUtil.isValue(message.getSex())){
                        setParams("sex",message.getSex());
                    }

                    requestData(Constants.GET_COACH_MEMBERS);
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消订阅，防止内存泄漏
        RxSubscriptions.remove(mSubscription);
    }


    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.GET_COACH_MEMBERS){
            MembersBean membersBean = (MembersBean)dataBean;
            memberAllNum.set(membersBean.getCount());

            List<MembersBean.ListBean> list = membersBean.getList();
            //清除旧数据
            if(curPage == FIRST_PAGE){
                observableList.clear();

            }

            if(list != null && list.size() > 0){
                for(MembersBean.ListBean bean : list){
                    MemberItemViewModel itemViewModel = new MemberItemViewModel(this,bean);
                    observableList.add(itemViewModel);
                }
            }

            if(observableList.size() > 0){
                if(list == null || list.size() == 0){
                    getUC().getFinishLoadMoreData().call();
                }
            }
        }

        if(code == Constants.OS_LIST){
            OsBeans osBeans = (OsBeans)dataBean;
            OsBeans.ListBean listBean = new OsBeans.ListBean();
            listBean.setOs_name("全部门店");
            osBeans.getList().add(0,listBean);
            osList.set(osBeans.getList());

            osUtils = new UnitBeanUtils<OsBeans.ListBean>() {
                @Override
                public String unit(OsBeans.ListBean o) {
                    return String.valueOf(o.getOs_id());
                }

                @Override
                public String unit_cn(OsBeans.ListBean o) {
                    return o.getOs_name();
                }
            };
        }

    }
}
